package com.woyao;

import android.Manifest;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.woyao.core.FileUtil;
import com.woyao.core.model.BaseResponse;
import com.woyao.core.model.DemandSummary;
import com.woyao.core.model.GetMoveResponse;
import com.woyao.core.model.GetMyDemandResponse;
import com.woyao.core.model.GetSubjectsResponse;
import com.woyao.core.model.Move;
import com.woyao.core.model.MyTag;
import com.woyao.core.service.AccountService;
import com.woyao.core.util.Common;
import com.woyao.core.util.ServiceFactory;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import retrofit2.Call;

import static android.view.View.GONE;
import static com.woyao.WoyaoooApplication.userId;

public class MoveActivity extends AppCompatActivity  {

    public boolean is_new = false;

    private RecyclerView recyclerView;
    private  MediaAdapter mediaAdapter;

    private RecyclerView mytagRecyclerView;
    private  MyTagAdapter mytagAdapter;
    
    private ProgressBar progress;

    Button deleteBtn;
    
    private TextView demandTitle;
    private Button addMediaBtn;
    private EditText descTxt;
    private  TextView caption;

    private LinearLayout actionArea;

    List<DemandSummary> demands = new ArrayList<DemandSummary>();
    
  
    ProgressDialog progressDialog;
    private Move current = new Move();

    private  boolean loading = false;

    Button nextBtn;
        
    Integer CHOOSE_MEDIA_CODE =  8;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_update);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(toolbar);
        final ActionBar ab = getSupportActionBar();
        ab.setDisplayShowHomeEnabled(true); // show or hide the default home button
        ab.setDisplayHomeAsUpEnabled(true);
        ab.setDisplayShowCustomEnabled(true); // enable overriding the default toolbar layout

        nextBtn = (Button) findViewById(R.id.update_finish);

        progress  =  (ProgressBar)  findViewById(R.id.uploading);

        caption =(TextView) findViewById(R.id.update_tag_caption);
        demandTitle =(TextView)   findViewById(R.id.id_update_demand_title);

        demandTitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (current.getId() == 0 ) {
                    presentDemandChoice();
                }
            }
        });

        actionArea =  (LinearLayout) findViewById(R.id.move_actions);

        mytagRecyclerView = (RecyclerView) findViewById(R.id.id_mytags);
        mytagRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.HORIZONTAL));//布局管理器
//        mytagRecyclerView.setLayoutManager(new GridLayoutManager(this,4));//布局管理器
        mytagRecyclerView.setItemAnimator(new DefaultItemAnimator());//使用默认的动画效果

      
        recyclerView = (RecyclerView) findViewById(R.id.updates_medias);
        recyclerView.setLayoutManager(new GridLayoutManager(this,4));//布局管理器
        recyclerView.setItemAnimator(new DefaultItemAnimator());//使用默认的动画效果
        mediaAdapter = new MediaAdapter(this, current.getMedias());
        mediaAdapter.setChangedHandler(new MediaAdapter.Changed() {
            @Override
            public void Changed(Integer count) {
                current.setMedias(mediaAdapter.getMedias());
            }
        });
        recyclerView.setAdapter(mediaAdapter);
        
        addMediaBtn = (Button) findViewById(R.id.update_add_media);

        addMediaBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                 addMedia();
                    


            }
        });

        
        descTxt = (EditText)findViewById(R.id.id_update_desc);

     

        nextBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finishIt();

            }
        });

        


        deleteBtn= (Button)findViewById(R.id.update_delete);
        deleteBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               

                Dialog alertDialog = new AlertDialog.Builder(MoveActivity.this).
                        setTitle("信息").
                        setMessage("删除吗？").
                        setIcon(R.drawable.ic_launcher).
                        setPositiveButton("确定", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                                deleteIt();
                            }
                        }).
                        setNegativeButton("取消", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        }).
                        create();
                alertDialog.show();

            }
        });



       
        Intent intent = getIntent();
        Integer id = intent.getIntExtra("id",0);



        if (id == 0 ) {
            String category = intent.getStringExtra("category");
            this.setTitle("发布业务动态");
            if (category.equals("demand")) {
                this.setTitle("发布业务需求");
                caption.setText("寻求资源：");
            }else if (category.equals("resource")) {
                this.setTitle("发布业务资源");
                caption.setText("提供资源：");
            }
            current.setCategory(category);

            loadSubjects( );
            loadDemands();

            actionArea.setVisibility(GONE);

        }else {
            loadData( id );
            addMediaBtn.setVisibility(View.INVISIBLE);
            descTxt.setEnabled(false);
            nextBtn.setVisibility(View.INVISIBLE);

        }



    }


    private void addMedia(){



        if(ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED){ //权限没有被授予
            /**3.申请授权
             * @param
             *  @param activity The target activity.（Activity|Fragment、）
             * @param permissions The requested permissions.（权限字符串数组）
             * @param requestCode Application specific request code to match with a result（int型申请码）
             *    reported to {@link OnRequestPermissionsResultCallback#onRequestPermissionsResult(
             *    int, String[], int[])}.
             * */
            Dialog alertDialog = new AlertDialog.Builder(this).
                    setTitle("信息").
                    setMessage( "为提供丰富动态信息，上传图片，请授权访问设备的图片资料").
                    setIcon(R.drawable.ic_launcher).
                    setPositiveButton("确定", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ActivityCompat.requestPermissions(MoveActivity.this,
                                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                    520);
                        }
                    }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                        }
                    }).
                    create();
            alertDialog.show();


        }else{//权限被授予
            Intent intent = new Intent();
            intent.setType("*/*");
            // start the image capture Intent
            intent.setAction(Intent.ACTION_GET_CONTENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            startActivityForResult(intent, CHOOSE_MEDIA_CODE);
        }

    }
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

        if (requestCode == 520)
        {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
            {
                Toast.makeText(MoveActivity.this, "请上传图片", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent();
                intent.setType("*/*");
                // start the image capture Intent
                intent.setAction(Intent.ACTION_GET_CONTENT);
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                startActivityForResult(intent, CHOOSE_MEDIA_CODE);
            } else
            {
                Toast.makeText(MoveActivity.this, "权限被拒绝，图片不能正常上传", Toast.LENGTH_SHORT).show();
            }
            return;
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    private void loadDemands(){

        AsyncTask<Void, Void, GetMyDemandResponse> task =new AsyncTask<Void, Void, GetMyDemandResponse>() {
            @Override
            protected GetMyDemandResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<GetMyDemandResponse> responseCall = svc.getMyDemand(WoyaoooApplication.userId, "true");
                try {
                    GetMyDemandResponse response = responseCall.execute().body();
                    return response;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }
            @Override
            protected void onPostExecute(final GetMyDemandResponse response) {

                demands = response.getContent();
                if (demands.size() > 0){
                    current.setDemand_id( demands.get(0).getId());
                    current.setDemand_title( demands.get(0).getTitle());
                    demandTitle.setText( current.getDemand_title());
                }
            }
            @Override
            protected void onCancelled() {
                progressDialog.dismiss();
            }
        };
        task.execute((Void)null);
    }

    int demandChoice = 0 ;
    private void presentDemandChoice( ){


        ArrayList<String> list = new ArrayList<String>();
        for (int i = 0; i < demands.size(); i++) {
            DemandSummary ds = demands.get(i);

            list.add(ds.getTitle());
        }


        String[] items =  (String[])list.toArray(new String[0]);

        AlertDialog.Builder singleChoiceDialog =
                new AlertDialog.Builder(MoveActivity.this);
        singleChoiceDialog.setTitle("选择业务");
        // 第二个参数是默认选项，此处设置为0
        singleChoiceDialog.setSingleChoiceItems(items, demandChoice,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        demandChoice = which;
                    }
                });
        singleChoiceDialog.setPositiveButton("确 定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (demandChoice != -1) {
                            current.setDemand_id(demands.get(demandChoice).getId()  );
                            current.setDemand_title( demands.get(demandChoice).getTitle());
                            demandTitle.setText( current.getDemand_title());

                        }
                    }
                });
        singleChoiceDialog.setNegativeButton("取 消",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
        singleChoiceDialog.show();

    }

    private void finishIt(){
        if (current.getId() > 0) {
            Intent intent = new Intent();
            setResult(0, intent);
            finish();
            return;
        }

        if ( mytagAdapter.getSelected().equals("")  ){

            Dialog alertDialog = new AlertDialog.Builder(MoveActivity.this).
                    setTitle("信息").
                    setMessage("请选择主题标签").
                    setIcon(R.drawable.ic_launcher).
                    setPositiveButton("确定", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    }).
                    create();
            alertDialog.show();

            return;
        }


        if (descTxt.getText().length() < 6){

            Dialog alertDialog = new AlertDialog.Builder(MoveActivity.this).
                    setTitle("信息").
                    setMessage("请填写具体信息，至少6个字").
                    setIcon(R.drawable.ic_launcher).
                    setPositiveButton("确定", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            descTxt.requestFocus();
                        }
                    }).
                    create();
            alertDialog.show();

            return;
        }



        addIt( );

    }
    


    private void loadSubjects( ){

        AsyncTask<Void, Void, GetSubjectsResponse> task =new AsyncTask<Void, Void, GetSubjectsResponse>() {
            @Override
            protected GetSubjectsResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<GetSubjectsResponse> responseCall = svc.getSubjects(userId,current.getCategory());
                try {
                    GetSubjectsResponse response = responseCall.execute().body();
                    return response;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }
            @Override
            protected void onPostExecute(final GetSubjectsResponse response) {
                if (response != null && response.getContent() !=null){



                    mytagAdapter = new MyTagAdapter( MoveActivity.this,getResources(),response.getContent());
                    mytagRecyclerView.setAdapter(mytagAdapter);
                }

            }
            @Override
            protected void onCancelled() {
            }
        };
        task.execute((Void)null);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent intent = new Intent();
        setResult(0, intent);
        finish();
        return true;
    }


    private void uploadVideo(  String  videoPathOrigin ,final String filename ){
        progress.setVisibility(View.VISIBLE);
        progress.setProgress( 10  );
//        String cachepath = Common.getDiskCachePath(this);

//        Common.cutMp4(1, 60*1000, videoPathOrigin, cachepath, filename);

//        final String videoPath  = cachepath + "/" + filename;
        final String videoPath  =   videoPathOrigin;
        TimerTask task = new TimerTask(){
            public void run(){
                progress.setProgress( 40  );
                final File file = new File(videoPath);
                if (file.length() < 1000) {
                    MoveActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            progress.setVisibility(View.INVISIBLE);
                            Common.alert(MoveActivity.this, "上传失败");
                        }
                    });
                    return;
                }

                OSS oss = FileUtil.getOss(getApplicationContext());
                PutObjectRequest put = new PutObjectRequest(FileUtil.videoBucketName, filename, videoPath);

// 异步上传时可以设置进度回调
                put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
                    @Override
                    public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                        progress.setProgress(  Math.round( 100* currentSize / totalSize)  );
                    }
                });

                OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
                    @Override
                    public void onSuccess(PutObjectRequest request, PutObjectResult result) {
//                Toast.makeText(DemandNewActivity.this,"上传成功",Toast.LENGTH_SHORT).show();
//                        Common.setDemandAttr(demand.getId(),"image","aliyun"+filename,"add");
                        final String videoUrl = "https://woyaooovideo.oss-cn-hangzhou.aliyuncs.com/" + filename;


                        MoveActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                progress.setProgress(  100  );
                                progress.setVisibility(View.INVISIBLE);
                                mediaAdapter.addMedia(  videoUrl ,"aliyun"+filename);
                            }
                        });


                    }

                    @Override
                    public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                        // 请求异常
                        if (clientExcepion != null) {
                            // 本地异常如网络异常等
                            clientExcepion.printStackTrace();
                        }
                        if (serviceException != null) {
                            // 服务异常

                        }

                        MoveActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Common.alert(MoveActivity.this,"上传失败");
                            }
                        });

                    }
                });

            }
        };
        Timer timer = new Timer();
        timer.schedule(task, 1000*3);
        progress.setProgress( 20  );



    }

    private void uploadImage( final String picturePath, final String filename ){
        progress.setVisibility(View.VISIBLE);
        OSS oss = FileUtil.getOss(getApplicationContext());
        PutObjectRequest put = new PutObjectRequest(FileUtil.bucketName, filename, picturePath);


// 异步上传时可以设置进度回调
        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                progress.setProgress(  Math.round( 100* currentSize / totalSize)  );
            }
        });

        OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                final String picUrl = "https://woyaooo1.oss-cn-hangzhou.aliyuncs.com/" + filename;
                MoveActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        progress.setProgress(  100  );
                        progress.setVisibility(View.INVISIBLE);
                        mediaAdapter.addMedia(  picUrl ,"aliyun"+filename);

                    }
                });

            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                // 请求异常
                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    clientExcepion.printStackTrace();
                }
                if (serviceException != null) {
                    // 服务异常

                }
                progress.setVisibility(View.INVISIBLE);
                Toast.makeText(MoveActivity.this,"上传失败",Toast.LENGTH_SHORT).show();
            }
        });

    }


    private void addIt(  ) {
        current.setMedias( mediaAdapter.getMedias() );
//        current.setSubject(  );
        current.setDescription( descTxt.getText().toString());

        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
//        progressDialog.setMessage("拼命加载中······");
        progressDialog.show();

        AsyncTask<Void, Void, BaseResponse> task = new AsyncTask<Void, Void, BaseResponse>() {
            @Override
            protected BaseResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);

                Call<BaseResponse> responseCall = svc.addMove(  userId,current.getDemand_id() ,mytagAdapter.getSelected(),current.getCategory(),current.getDescription(), Common.getMediaIds(current.getMedias()));
                BaseResponse response = null;
                try {
                    response = responseCall.execute().body();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return response;
            }

            @Override
            protected void onPostExecute(final BaseResponse response) {
                if (response != null ){

                    if ( response.isSuccess()) {

                        Dialog alertDialog = new AlertDialog.Builder(MoveActivity.this).
                                setTitle("信息").
                                setMessage("已经发布，将展示给关注您朋友").
                                setIcon(R.drawable.ic_launcher).
                                setPositiveButton("确定", new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        Intent intent = new Intent();
                                        setResult(666, intent);
                                        finish();
                                    }
                                }).
                                create();
                        alertDialog.show();
                    }
                    else{
                        Common.alert(MoveActivity.this,response.getMessage());

                    }
                } else {
                    Common.alert( MoveActivity.this, "系统发生错误");
                }
                progressDialog.dismiss();
            }
            @Override
            protected void onCancelled() {
                progressDialog.dismiss();
            }
        };
        task.execute((Void) null);
    }



    private void loadData( final Integer theid ) {
        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("正在获取数据······");
        progressDialog.show();

        AsyncTask<Void, Void, GetMoveResponse> task = new AsyncTask<Void, Void, GetMoveResponse>() {
            @Override
            protected GetMoveResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);

                Call<GetMoveResponse> responseCall = svc.getMove(userId,theid);
                GetMoveResponse response = null;
                try {
                    response = responseCall.execute().body();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return response;
            }

            @Override
            protected void onPostExecute(final GetMoveResponse response) {
                if (response != null && response.getContent() != null) {
                    renderIt( response) ;
                }
                progressDialog.dismiss();
            }
            @Override
            protected void onCancelled() {
                progressDialog.dismiss();
            }
        };
        task.execute((Void) null);
    }

    private void renderIt(GetMoveResponse response) {

        progressDialog.dismiss();


        current = response.getContent();

        List<MyTag> subs =  new ArrayList<MyTag>();
        for ( String sub : response.getContent().getSubject()){
            MyTag tg = new MyTag();
            tg.setId(sub);
            tg.setSubject( sub);
            tg.setSelected(true);
            subs.add( tg);
        }

        mytagAdapter = new MyTagAdapter( MoveActivity.this,getResources(),subs);
        mytagRecyclerView.setAdapter(mytagAdapter);

        demandTitle.setText( current.getDemand_title());
        descTxt.setText(current.getDescription());

        mediaAdapter = new MediaAdapter(this, current.getMedias());
        mediaAdapter.setChangedHandler(new MediaAdapter.Changed() {
            @Override
            public void Changed(Integer count) {

            }
        });
        recyclerView.setAdapter(mediaAdapter);


    }


    public  void deleteIt(  ) {
        AsyncTask<Void, Void, BaseResponse> task = new AsyncTask<Void, Void, BaseResponse>() {
            @Override
            protected BaseResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<BaseResponse> responseCall = svc.deleteMove(WoyaoooApplication.userId,current.getId());
                BaseResponse ret = null ;
                try {
                    ret = responseCall.execute().body();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return ret;
            }

            @Override
            protected void onPostExecute(final BaseResponse response) {
                if (response != null) {
                    if (response.isSuccess()){
                        Common.showSnack(MoveActivity.this, deleteBtn, response.getMessage());
                        Intent intent = new Intent();
                        setResult(666, intent);
                        finish();
                    }else{
                        Common.showSnack(MoveActivity.this, deleteBtn, response.getMessage());
                    }
                } else {
                    Common.alert( MoveActivity.this,"系统发生错误");
                }
            }

            @Override
            protected void onCancelled() {
            }
        };
        task.execute((Void) null);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data){
        super.onActivityResult(requestCode, resultCode, data);


         if(requestCode == CHOOSE_MEDIA_CODE){
            try{
                Uri selectedImage = data.getData();
                String localpicpath = Common.getPath(MoveActivity.this,selectedImage);
                if (localpicpath.endsWith("mp4")){
                    uploadVideo(  localpicpath, FileUtil.getVideoObjectKey());
                }else {
                    uploadImage(localpicpath, FileUtil.getPicObjectKey());
                }
            }catch(Exception e) {
                e.printStackTrace();
            }
            
        }

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent();
            setResult(0, intent);
            finish();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }


}
